package com.example.webchar.webchar.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.shiro.authc.AuthenticationException;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: boot
 * @description
 * @author: YouName
 * @create: 2021-03-24 11:57
 **/
public class JwtUtil {

    /**
     * 过期的时间
     */
    private static final long EXPIRE_TIME = 1000 * 60 * 30;

    /**
     * 校验token是否正确
     *
     * @param token    密钥
     * @param password 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String username, String password) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需password解密也能获得
     *
     * @return token中包含的用户名
     */

    /**
     * 生成签名,30min后过期
     *
     * @param username 用户名
     * @param password 用户的密码
     * @return 加密的token
     */
    public static String sign(int id, String username, String password) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 附带username信息
        return JWT.create()
                .withClaim("username", username)
                .withClaim("id", id)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static String subStringToken(HttpServletRequest request) {
        try {
            return request.getHeader("Authorization");
        } catch (Exception e) {
            throw new AuthenticationException("没有token");
        }
    }

}

